package com.example.im.controller;

import com.example.im.entity.ChatMessage;
import com.example.im.service.ChatMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/chat")
public class ChatController {
    @Autowired
    private ChatMessageService chatMessageService;

    @GetMapping("/history")
    public ResponseEntity<List<ChatMessage>> getChatHistory(
            @RequestParam String user1,
            @RequestParam String user2,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size) {
        
        // 获取最近的消息，按时间倒序
        List<ChatMessage> messages = chatMessageService.getChatHistory(
            user1, user2, PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "timestamp"))
        );
        
        return ResponseEntity.ok(messages);
    }

    @GetMapping("/messages")
    public List<ChatMessage> getUserMessages(@RequestParam String username) {
        return chatMessageService.getUserMessages(username);
    }

    @GetMapping("/unread")
    public List<ChatMessage> getUnreadMessages(@RequestParam String username) {
        return chatMessageService.getUnreadMessages(username);
    }

//    @PostMapping("/messages")
//    public ChatMessage saveMessage(@RequestBody ChatMessage message) {
//        return chatMessageService.saveMessage(message);
//    }
} 